=begin
    This file is part of GSRuby.

    GSRuby is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    GSRuby is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with GSRuby.  If not, see <http://www.gnu.org/licenses/>.
=end

=begin
    Simple bot that publish from RSS feed

    USAGE:
    - Edit the variables node, user and password
    - Edit filename, this is a plain text file used to
      store the date of last notice published
    - Edit url, this should be the url of the RSS feed
    - Remove 'ssl: true' if your instance doesn't use SSL
    - Add 'ssl_insecure: true' if your instance uses a 
      self-signed cert
    - Finally, you can setup this script in a cron job
      for publish automatically, the following example checks 
      the RSS and publish if there is news each 15 min
        $ crontab -e
        */15 * * * * cd /path/to/script/dir && ruby ./rss-bot.rb
=end

require 'rss'
require 'gsruby'

node = 'https://yourinstance.tld'
user = 'your_username'
passwd = 'your_password'
filename = 'my-rss-bot.txt'
url = 'https://anydomain.tld/feed/'

# Creates a new GNU Social object
session = GNUSocial::Client.new(node,user,passwd, ssl: true)

# Open a file for read/write the last notice that we have published
if File.exist?(filename)
    file = File.open(filename,'r+')
else
    file = File.open(filename,'w+')
end

# Try to read, if fails continues without last notice
begin
    last = Time.parse(file.readline)
rescue EOFError
    last = Time.gm(0)
end

uri = URI(url)
feed = RSS::Parser.parse(Net::HTTP.get(uri),false)

feed.items.reverse_each do |item|
    if item.pubDate > last
        session.send_status "#{item.title}\n#{link}"
    end
end

# Update the file with the last notice published
file.rewind
file.write(feed.items[0].pubDate)
file.close
